import { MessagePlugin } from 'tdesign-vue';
import { TOKEN_NAME } from '@/config/global';
import request from '@/utils/request';
import router from '@/router';

const InitUserInfo = {
  roles: [],
};

// 用户名到角色的映射
// const roleMapping: { [username: string]: string[] } = {
//   admin: ['ALL_ROUTERS'],
//   user: ['DashboardBase', 'UserIndex', 'ALL_ROUTERS'],
//   // 可以根据需要添加更多用户和角色
// };

// 定义的state初始值
const state = {
  token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
  userInfo: InitUserInfo,
};

const mutations = {
  setToken(state, token) {
    localStorage.setItem(TOKEN_NAME, token);
    state.token = token;
  },
  removeToken(state) {
    localStorage.removeItem(TOKEN_NAME);
    state.token = '';
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
};

// actions
const actions = {
  async login({ commit }, userInfo) {
    const isMock = true;
    if (isMock) {
      // 模拟登录逻辑
      const mockLogin = async (userInfo) => {
        console.log('Mock login:', userInfo);
        return {
          code: 200,
          message: '登陆成功',
          data: 'main_token',
        };
      };

      const res = await mockLogin(userInfo);
      if (res.code === 200) {
        commit('setToken', res.data);
      } else {
        MessagePlugin.error(res.message);
        throw res;
      }
    } else {
      // 真实登录请求
      try {
        const response = await request.post('/user/login/', {
          username: userInfo.account,
          password: userInfo.password,
          phone: userInfo.phone,
          verify_code: userInfo.verifyCode,
        });
        if (response.status === 200) {
          commit('setToken', response.data.tokens.access);
          MessagePlugin.success(response.data.message);
        } else {
          MessagePlugin.error(response.data.message);
        }
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    }
  },

  async getUserInfo({ commit, state }) {
    const isMock = true;
    if (isMock) {
      // 模拟获取用户信息
      const mockRemoteUserInfo = async (token) => {
        if (token === 'main_token') {
          return {
            name: 'td_main',
            roles: ['ALL_ROUTERS'],
          };
        }
        return {
          name: 'td_dev',
          roles: ['UserIndex', 'DashboardBase', 'login'],
        };
      };

      const res = await mockRemoteUserInfo(state.token);
      commit('setUserInfo', res);
    } else {
      // 真实获取用户信息请求
      try {
        const response = await request.get('/user/user_info/', {
          headers: {
            Authorization: `Bearer ${state.token}`,
          },
        });
        if (response.status === 200) {
          const userInfo = response.data;
          // 基于前端逻辑分配角色
          // const roles = roleMapping[userInfo.username] || [];
          const roles = userInfo.roles || [];
          commit('setUserInfo', { ...userInfo, roles });
        } else {
          // 如果获取用户信息失败，则跳转到登录页面
          router.push('/login');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    }
  },

  async logout({ commit }) {
    const isMock = true;
    if (isMock) {
      // 模拟登出逻辑
      commit('removeToken');
      commit('setUserInfo', InitUserInfo);
    } else {
      // 真实登出请求
      try {
        await request.post(
          '/api/user/logout/',
          {},
          {
            headers: {
              Authorization: `Bearer ${state.token}`,
            },
          },
        );
        commit('removeToken');
        commit('setUserInfo', InitUserInfo);
      } catch (error) {
        console.error('登出失败:', error);
        throw error;
      }
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
